package com.hyl.interceptorbase;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * 请求统一的拦截,需要做的事情
 * 统计请求到响应的时间
 * 请求的路径
 * 请求的参数
 * @author HYL
 * @create 2017-06-15 上午9:47
 **/
public class RequestInterceptorBase extends HandlerInterceptorAdapter{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获得请求开始的时间
        Long start = System.currentTimeMillis();
        request.setAttribute("startTime",start);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        StringBuilder sb=new StringBuilder();

        //获得访问的url
        StringBuffer requestURL = request.getRequestURL();
        //获得请求的参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        StringBuffer str=new StringBuffer();
        for (Map.Entry<String, String[]> entry : entries) {
            str.append("{").append(entry.getKey()).append(":").append(Arrays.toString(entry.getValue())).append("}").append("\r\n");
        }
        //获得请求的时间
        Long startTime = (Long) request.getAttribute("startTime");
        Long endTime = System.currentTimeMillis();
        sb.append("\r\n").append("\r\n").append("***********************************************************************************").append("\r\n").append("\r\n");
        sb.append("Action Report: ----------------  ")
                .append(new Date().toString())
                .append("  ----------------")
                .append("\r\n")
                .append("Request URL:")
                .append(requestURL)
                .append("\r\n")
                .append("Parameters:")
                .append("\r\n")
                .append(str)
                .append("\r\n")
                .append("本次请求处理时间为：")
                .append((endTime-startTime))
                .append("豪秒")
                .append("\r\n")
                .append("\r\n");
        sb.append("***********************************************************************************").append("\r\n");
        sb.append("```````````````````````````````````````````````````````````````````````````````````")
                .append("\r\n")
                .append("\r\n")
                .append("\r\n")
                .append("\r\n");
        request.removeAttribute("startTime");
        System.out.println(sb.toString());

    }
}
